﻿using System.ComponentModel;
using Gildor.SimpleHostMonitor.Desktop.Entities;

namespace Gildor.SimpleHostMonitor.Desktop
{
    /// <summary>
    /// The comparer used in a list view to compare <see cref="Gildor.SimpleHostMonitor.Desktop.HostInfo"/> instances.
    /// </summary>
    public class HostInfoComparer : ListViewCustomComparer<HostInfo>
    {
        /// <summary>
        /// Compares the specified <see cref="Gildor.SimpleHostMonitor.Desktop.HostInfo"/> instances.
        /// </summary>
        /// <param name="x">One <see cref="Gildor.SimpleHostMonitor.Desktop.HostInfo"/> instance.</param>
        /// <param name="y">The other <see cref="Gildor.SimpleHostMonitor.Desktop.HostInfo"/> instance.</param>
        /// <returns></returns>
        public override int Compare (HostInfo x, HostInfo y)
        {
            //If x and y is the same object, return 0.
            //Fixed the issue TargetInvocationException:
            //{"IComparer (or the IComparable methods it relies upon) did not return zero when Array.Sort called x. CompareTo(x). x: 'Gildor.SimpleHostMonitor.Desktop.HostInfo'  x's type: 'HostInfo' The IComparer: 'Gildor.SimpleHostMonitor.Desktop.HostInfoComparer'."}
            if (object.ReferenceEquals (x, y))
            {
                return 0;
            }

            //The prefix to control the sort direction.
            int prefix = (SortDirection == ListSortDirection.Ascending) ? 1 : -1;

            //Calc the result according to the sort field.
            switch (SortBy)
            {
                case "Address":
                    return prefix * x.Address.CompareTo (y.Address);
                //break;
                case "State":
                    int xTime, yTime;
                    if (int.TryParse (x.State.Substring (0, x.State.Length - 2), out xTime) && int.TryParse (y.State.Substring (0, y.State.Length - 2), out yTime))
                    {
                        return prefix * xTime.CompareTo (yTime);
                    }
                    else
                    {
                        return prefix * x.State.CompareTo (y.State);
                    }
                //break;
                default:
                    return 0;
                //break;
            }
        }
    }
}
